import { Component, OnInit } from '@angular/core';
import { ConfirmationService, MessageService } from 'primeng/api';
import { ApiMenuService } from 'src/app/service/menu.service';

@Component({
    selector: 'app-api-manage',
    templateUrl: './api-manage.component.html',
    styleUrls: ['./api-manage.component.scss'],
    providers: [ConfirmationService, MessageService],
})
export class ApiManageComponent implements OnInit {
    tableData: any;
    originData: any;
    modalTitle: any;
    display = false;
    currentItem: any;
    form = {
        name: '',
        desc: '',
        link: '',
        method: '',
        sort: 0,
        url: '',
    };
    editForm = {
        roleName: '',
        description: '',
    };
    mode: string;
    constructor(
        private apiMemuService: ApiMenuService,
        private confirmationService: ConfirmationService,
        private messageService: MessageService
    ) {}

    ngOnInit(): void {
        this.search();
    }
    validateUrl = (url) => {
        // const res = routerConfigs.findIndex(item => item.path === url)
        // if (res < 0) {
        //   ElMessage({
        //     type: 'error',
        //     message: '相关链接不正确',
        //   })
        //   return false
        // }
        return true;
    };
    validateSort = (sort) => {
        const res = this.originData
            .filter((item) =>
                this.mode === 'edit'
                    ? item.backendApiId !== this.currentItem.backendApiId
                    : true
            )
            .findIndex((item) => item.backendApiSort == sort);
        if (res >= 0) {
            this.messageService.add({
                severity: 'error',
                summary: '警告',
                detail: '排序编号有重复',
            });
            this.search();
            return false;
        }
        return true;
    };
    validate = () => {
        if (
            !this.form.desc ||
            !this.form.sort ||
            (!this.form.method && this.mode !== 'normal') ||
            !this.form.name ||
            !this.form.link
        ) {
            this.messageService.add({
                severity: 'error',
                summary: '警告',
                detail: '必须项不能为空',
            });
            return false;
        }
        let url = this.form.link;
        let sort = this.form.sort;
        // if (mode.value === 'add') {
        //   url = (currentItem.value.frontendMenuUrl || '') + url
        // }
        return (
            (this.mode === 'add' ? this.validateUrl(url) : true) &&
            this.validateSort(sort)
        );
    };
    async search() {
        // const it = await fetchPostById({ id: id.value })
        // currentItem.value = it || {}
        const r = await this.apiMemuService.fetchApiListByNone();
        const genChildList = (list) => {
            const res = [];
            list.forEach((item) => {
                if (!item.pid) {
                    let temp = { data: null, children: [], expanded: true };
                    temp.data = item;
                    res.push(temp);
                }
            });
            list.forEach((item) => {
                if (item.pid) {
                    const it = res.find(
                        (it) => it.data.backendApiId === item.pid
                    );
                    if (it) {
                        let temp = { data: null };
                        temp.data = item;
                        it.children = (it.children || []).concat(temp);
                    }
                }
            });
            return res;
        };
        this.tableData = genChildList(r);
        console.log(this.tableData);
        this.originData = r;
    }
    openDialog(e, item?) {
        this.display = true;
        if (e == 'normal') {
            this.modalTitle = '新增API组';
            this.mode = 'normal';
            this.form.name = '';
            this.form.link = 'none';
            this.form.method = '';
            this.form.sort = null;
            this.form.desc = '';
        } else if (e == 'edit') {
            this.currentItem = item;
            console.log(item);
            this.modalTitle = '编辑API';
            this.mode = 'edit';
            this.form.name = item.backendApiName;
            this.form.link = item.backendApiUrl;
            this.form.method = item.backendApiMethod;
            this.form.sort = item.backendApiSort;
            this.form.desc = item.description;
        } else {
            this.currentItem = item;
            this.modalTitle = '新增API';
            this.mode = 'add';
            this.form.name = '';
            this.form.link = '';
            this.form.method = '';
            this.form.sort = null;
            this.form.desc = '';
        }
    }
    async delete(id) {
        this.confirmationService.confirm({
            message: '请问你确认删除吗 ?此操作无法恢复，建议由开发人员执行。',
            header: '警告',
            icon: 'pi pi-exclamation-triangle',
            accept: async () => {
                const res = await this.apiMemuService.deleteApiById({ id });
                if (res.code === '200') {
                    this.messageService.add({
                        severity: 'success',
                        summary: '确认',
                        detail: '你已经删除',
                    });
                    this.search();
                }
            },
        });
    }
    async submit() {
        let res;
        if (!this.validate()) {
            return;
        }
        if (this.mode === 'normal') {
            res = await this.apiMemuService.addApiByConfig({
                pid: '',
                description: this.form.desc,
                backendApiName: this.form.name,
                backendApiSort: this.form.sort,
                backendApiMethod: this.form.method,
                backendApiUrl: this.form.link,
            });
        } else if (this.mode === 'edit') {
            res = await this.apiMemuService.editApiByConfig({
                description: this.form.desc,
                backendApiId: this.currentItem.backendApiId,
                pid: this.currentItem.pid,
                backendApiSort: this.form.sort,
                backendApiMethod: this.form.method,
                backendApiUrl: this.form.link,
                backendApiName: this.form.name,
            });
        } else if (this.mode === 'add') {
            res = await this.apiMemuService.addApiByConfig({
                description: this.form.desc,
                backendApiName: this.form.name,
                backendApiSort: this.form.sort,
                backendApiMethod: this.form.method,
                backendApiUrl: this.form.link,
                pid: this.currentItem.backendApiId,
            });
        }
        if (res && res.code === '200') {
            this.messageService.add({
                severity: 'success',
                summary: '确认',
                detail: '已经完成操作',
            });
            this.display = false;
            this.search();
        }
    }
}
